class Solution {
    TreeNode* __buildTree(vector<int>& inorder, int left1, int right1,
        vector<int>& postorder, int left2, int right2)
    {
        if (right2 < left2) return nullptr;
        if (right2 == left2) return new TreeNode(postorder[left2]);
        int rootNum = postorder[right2];
        TreeNode* node = new TreeNode(rootNum);
        int index;
        for (index = left1; index <= right1; ++index)
        {
            if (inorder[index] == rootNum) break;
        }
        int leftSize = index - left1;
        int rightSize = inorder.size() - index + 1;
        node->left = __buildTree(inorder, left1, index - 1,
            postorder, left2, left2 + leftSize - 1);
        node->right = __buildTree(inorder, index + 1, right1,
            postorder, left2 + leftSize, right2 - 1);
        return node;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return __buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }
};